import React from 'react';
import ReactDOM from 'react-dom/client';
import { MamisCopilotConfig } from '../types/config';
import { ShadowDOMManager } from '../isolation/ShadowDOMManager';
import CopilotKitWrapper from './CopilotKitWrapper';

/**
 * 主要的麦米思 AI 助手组件
 */
export class MamisCopilotWidget {
  private config: MamisCopilotConfig;
  private shadowManager: ShadowDOMManager;
  private reactRoot: ReactDOM.Root | null = null;
  private popupContainer: HTMLElement | null = null;

  constructor(config: MamisCopilotConfig, shadowManager: ShadowDOMManager) {
    this.config = config;
    this.shadowManager = shadowManager;

    this.setupKeyboardShortcuts();
  }

  /**
   * 渲染组件
   */
  render(): void {
    this.createCopilotKit();
    this.injectStyles();
  }

  /**
   * 创建 CopilotKit
   */
  private createCopilotKit(): void {
    // 创建CopilotKit容器
    this.popupContainer = this.shadowManager.createElement('div', {
      id: 'mamis-copilot-container',
      className: 'mamis-copilot-container',
      styles: this.getPopupContainerStyles(),
    });

    // 渲染 React CopilotKit 组件
    this.reactRoot = ReactDOM.createRoot(this.popupContainer);
    this.reactRoot.render(
      React.createElement(CopilotKitWrapper, {
        config: this.config,
        shadowManager: this.shadowManager,
        onMessage: (message: unknown) => {
          if (this.config.onMessage) {
            this.config.onMessage(message);
          }
        },
        onPageAction: (action: string, target: string, result: unknown) => {
          if (this.config.onPageAction) {
            this.config.onPageAction(action, target, result);
          }
        },
        onError: (error: Error) => {
          if (this.config.onError) {
            this.config.onError(error);
          }
        },
      })
    );

    this.shadowManager.getShadowRoot().appendChild(this.popupContainer);
  }

  /**
   * 注入样式
   */
  private injectStyles(): void {
    const styles = `
      .mamis-copilot-container {
        position: fixed;
        z-index: ${this.config.zIndex};
        pointer-events: auto;
      }
      .mamis-copilot-container button.copilotKitCodeBlockToolbarButton {
        height: inherit;
      }
    `;

    this.shadowManager.injectStyles(styles, 'mamis-copilot-main-styles');
  }

  /**
   * 获取CopilotKit容器样式
   */
  private getPopupContainerStyles(): string {
    const position = this.config.trigger.position;
    let positionStyles = '';

    // 根据配置的位置设置CopilotKit的位置
    switch (position) {
      case 'bottom-right':
        positionStyles = 'bottom: 20px; right: 20px;';
        break;
      case 'bottom-left':
        positionStyles = 'bottom: 20px; left: 20px;';
        break;
      case 'top-right':
        positionStyles = 'top: 20px; right: 20px;';
        break;
      case 'top-left':
        positionStyles = 'top: 20px; left: 20px;';
        break;
      default:
        positionStyles = 'bottom: 20px; right: 20px;';
    }

    return `
      ${positionStyles}
    `;
  }

  /**
   * 设置键盘快捷键（CopilotKit 内置支持快捷键）
   */
  private setupKeyboardShortcuts(): void {
    // CopilotKit 内置快捷键支持，这里可以添加额外的快捷键逻辑
    // 暂时保留此方法以备将来扩展
  }

  /**
   * 更新配置
   */
  updateConfig(newConfig: MamisCopilotConfig): void {
    this.config = newConfig;

    // 重新渲染 CopilotKit 组件
    if (this.reactRoot) {
      this.reactRoot.render(
        React.createElement(CopilotKitWrapper, {
          config: this.config,
          onMessage: (message: unknown) => {
            if (this.config.onMessage) {
              this.config.onMessage(message);
            }
          },
          onPageAction: (action: string, target: string, result: unknown) => {
            if (this.config.onPageAction) {
              this.config.onPageAction(action, target, result);
            }
          },
          onError: (error: Error) => {
            if (this.config.onError) {
              this.config.onError(error);
            }
          },
        })
      );
    }
  }

  /**
   * 销毁组件
   */
  destroy(): void {
    if (this.reactRoot) {
      this.reactRoot.unmount();
      this.reactRoot = null;
    }
  }

  /**
   * 获取当前状态
   */
  getState(): {
    config: MamisCopilotConfig;
  } {
    return {
      config: this.config,
    };
  }
}
